﻿<html debug="true">
    <head>
        <title>RSS Reader Demo Using Google Gears</title>

        <link rel="stylesheet" type="text/css" href="css/reader.css"/>
        <script src="scripts/gears_init.js" type="text/javascript"></script>
        <script src="firebug/firebug.js" type="text/javascript"></script>
        <script src="scripts/go_offline.js" type="text/javascript"></script>
        <script src="scripts/gears_db.js" type="text/javascript"></script>
        <script src="scripts/tests_setup.js" type="text/javascript"></script>
        <script src="scripts/overlay.js" type="text/javascript"></script>
        <script type="text/javascript" src="scripts/jquery.js"></script>
        <script type="text/javascript" src="scripts/jquery.jfeed.js"></script>
        <script>
          if (!window.google || !google.gears) {
            location.href = "http://gears.google.com/?action=install&message=You require Google Gears to run this Application" +
                "&return=http://hydws0011/googlegears/index.html";
          }
        </script>

        <script type="text/javascript">
            var oldFeedDiv;
            var IS_USER_ONLINE;
            var forceOffline;

            function __isUserOnline() {
                 $.ajax({
                   type: "POST",
                   url: "network.txt",
                   timeout: 5000,
                   cache: false,
                   success: function(msg){
                     if (forceOffline != true) {
                        IS_USER_ONLINE = true;
                   } else {
                        IS_USER_ONLINE = false;
                   }
                    //console.info('ONLINE');
                   },
                   error:function (XMLHttpRequest, textStatus, errorThrown) {
                            // typically only one of textStatus or errorThrown
                            // will have info
                            IS_USER_ONLINE = false;
                            //console.info('OFFLINE');
                    }
                 });
            }

            function loadFeeds() {
                showLoading();
                __getFeedsFromDb();
            }

            function __getFeedsFromDb() {
                db = new GearsDB('feedreader');
                db.selectAll('select * from feeds', null, function(feed) {
                   if (feed != null) {
                       var html =  "";
                       html += '<div class="unselectedFeed" onclick="getFeed(this,' + feed.id + ')">' + feed.title + '</div>';
                       document.getElementById('feedListContainer').innerHTML += html;
                   } else {
                       document.getElementById('feedListContainer').innerHTML = "";
                   }
                });
                $(".unselectedFeed").hover(
                    function () {
                        $(this).addClass("hover");
                    },
                    function () {
                        $(this).removeClass("hover");
                    }
                );
            }

            function getFeed(feedDiv, feedId) {
                if (oldFeedDiv != null) oldFeedDiv.className = "unselectedFeed";
                oldFeedDiv = feedDiv;

                feedDiv.className = "selectedFeed";

                var dbRef3 = new GearsDB('feedreader');
                var globalItemId = "";
                var html = "";

                dbRef3.selectRows('feeds', 'id = ?', [feedId], function(feed) {
                    html += '<div class="titlebar">';
                    html += '<div class="title"><a href="' + feed.link + '">' + feed.title + '</a></div>';
                    html += '<div class="description">' + feed.description + '</div>';
                    html += '</div><div class="entries">';
                });


                dbRef3.selectRows('feed_items', 'feed_id = ?', [feedId], function(item) {
                    itemId = item.id;
                    globalItemId = feedId;

                    var entry = [];
                    entry.link    = item.item_link;
                    entry.title   = item.item_title;
                    entry.content = item.item_description;

                    html += '<div class="entryTitle"><a href="' + entry.link + '">' + entry.title + '</a></div>';
                    html += '<div class="entryText">' + entry.content + '</div>';
                });
                html += "</div>";
                document.getElementById("feedContent").innerHTML = html;
            }

            function checkIfFeedExists(feedUrl) {
                var dbRef1 = new GearsDB('feedreader');
                var globalFeedId = "";
                dbRef1.selectRows('feeds', 'feedUrl = ?', [feedUrl], function(feed) {
                    if (feed != null) {
                        feedId = feed.id;
                        globalFeedId = feedId;
                    }
                });
                if (globalFeedId != 0) {
                    console.log('DB: Feed Id Already in database');
                    return true;
                } else {
                    console.log('DB: Feed Id not found in database. Prepare to add it now...');
                    return false;
                }
            }

            function addFeedDataToDB(feed, feedUrl) {
                console.log("addFeedDataToDB - " + feed.title + "-" + feedUrl);
                var dbRef = new GearsDB('feedreader');
                var feedData = {feedtype: feed.type, title: feed.title, feedUrl: feedUrl, link: feed.link, description: feed.description, updated: feed.updated};
                var result = dbRef.insertRow('feeds', feedData);
                //var result = dbRef.insertRow('feeds', feedData, 'title = ?', [feed.title]);
                console.log('DB: addFeedDataToDb result is: ' + result);
                if (result != undefined && result == 0) {
                    alert('Row already exists in the DB');
                }
                lId = dbRef.db.lastInsertRowId;
                console.log('feed added successfully to feed table and id is ' + lId);
                console.log('addFeedDataToDB: lastInsertedRowId is - ' + lId);
                return lId;
            }

            function updateStatus(status) {
                var dbRef =  new GearsDB('feedreader');
                var pref  = db.selectRow('preferences', 'id = 1');
                pref.online = status;
                dbRef.updateRow('preferences', pref);
            }

            function getStatus() {
                var dbRef =  new GearsDB('feedreader');
                db.selectAll('select * from preferences', null, function(pref) {
                    if(pref.online == 'N') {
                        IS_USER_ONLINE = false;
                    } else if (pref.online == 'Y') {
                        IS_USER_ONLINE = true;
                    }
                });
            }

            function deleteAllFeedsFromDB() {
                dbRef4 =  new GearsDB('feedreader');
                eR1 = dbRef4.emptyTable('feeds');
                alert(typeof(eR1));
                console.log(eR1);
                eR2 = dbRef4.emptyTable('feed_items');
                console.log(eR2);
                loadFeeds();
            }

            function deleteTables() {
                dbRef6 =  new GearsDB('feedreader');
                eR1 = dbRef6.emptyTable('feeds');
                eR2 = dbRef6.emptyTable('feed_items');
                eR3 = dbRef6.emptyTable('preferences');
                dbRef6.dropTable('feeds');
                dbRef6.dropTable('feed_items');
                dbRef6.dropTable('preferences');
                loadFeeds();
            }

            function addFeed(feedUrl) {
                var c = checkIfFeedExists(feedUrl);
                if (c) {
                    alert('Feed Already Available in Database');
                    return;
                }
                jQuery.getFeed({
                    url: 'php/proxy.php?url=' + feedUrl,
                    success: function(feed) {
                        console.log("DEBUG:  Feed Link  - " + feed.link        + " | " +
                                            "Feed Title - " + feed.title       + " | " +
                                            "Feed Url   - " + feedUrl          + " | " +
                                            "Feed Type  - " + feed.type        + " | " +
                                            "Feed Ver   - " + feed.version     + " | " +
                                            "Feed Desc  - " + feed.description + " | " +
                                            "Feed Upd   - " + feed.updated     + " | " +
                                            "Feed lang  - " + feed.language
                                    );
                        rowInsertedId = addFeedDataToDB(feed, feedUrl);
                        console.log('addFeed: rowInsertedId is ' + rowInsertedId);
                        var dbRef2 = new GearsDB('feedreader');
                        console.log('feed items length is ' + feed.items.length);
                        for(var i = 0; i < feed.items.length; i++) {
                            var item = feed.items[i];
                            /*
                            console.log("DEBUG: Item Title - " + item.title       + " | " +
                                               "Item Link  - " + item.link        + " | " +
                                               "Item Desc  - " + item.description + " | " +
                                               "Item Upd   - " + item.updated
                                        );
                            */
                            var itemData = {feed_id: rowInsertedId, item_title: item.title, item_link: item.link, item_description: item.description, item_updated: item.updated};
                            var result2 = dbRef2.insertRow('feed_items', itemData, 'item_link = ?', [item.link]);
                        }
                        document.getElementById('feedListContainer').innerHTML  = '';
                        loadFeeds();
                    }
                });
            }

            function showError() {
                var html = "";
                html += '<table width="100%" height="100%">';
                html += '<tr><td valign="middle" align="center" class="error">';
                html += 'An error occured';
                html += '</td></tr></table>';
                showSomething(html);
            }

            function showLoading() {
                var html = "";
                html += '<table width="100%" height="100%">';
                html += '<tr><td valign="middle" align="center" class="status">';
                html += 'Loading feeds...';
                html += '</td></tr></table>';
                showSomething(html);
            }

            function showNothing() {
                var html = "";
                html += '<table width="100%" height="100%">';
                html += '<tr><td valign="middle" align="center" class="status">';
                html += 'Click on a feed in the left sidebar or add a subscription...';
                html += '</td></tr></table>';
                showSomething(html);
            }

            function showSomething(html) {
                document.getElementById("feedContent").innerHTML = html;
            }

            function showOfflineNotification(idOfTableCallingOverlay) {
                prepareOverlay('cplanContent', 445, 200, idOfTableCallingOverlay);
            }

            function checkIfFirstVisit() {
                var db = google.gears.factory.create('beta.database', '1.0');
                db.open('feedreader');
                try {
                    db.execute("select * from preferences");
                } catch (e) {
                    initDb();
                }
            }


            $(document).ready(function(){
                checkIfFirstVisit();
                init();
                __isUserOnline();
                createOverlay();
                loadFeeds();
                setInterval("__isUserOnline()", 3000);
                $("#addSubLink").click(function () {
                    getStatus();
                    if (IS_USER_ONLINE) {
                        $("#addSubBox").show();
                    } else {
                        prepareOverlay('offlinenotificationoverlay', 445, 200, addSubLink);
                    }
                });
                $("#addSubX").click(function () {
                    $("#addSubBox").hide();
                });
                $("#add").click(function () {
                    //get the value entered by user, send it to jfeed, if valid and all good
                    //add to db, close the addSub box, wipe out left column, call load feed again
                    feedUrl = $("#addSubTxt").val();
                    addFeed(feedUrl);
                    $("#addSubBox").hide();
                });
                $("#delF").click(function () {
                    deleteAllFeedsFromDB();
                });
                $("#createTables").click(function () {
                    initDb();
                });
                $("#deleteTables").click(function () {
                    deleteTables();
                });
                $("#removeStore").click(function () {
                    removeStore();
                });
                $("#goOnline").click(function () {
                    //forceOffline = false;
                    //__isUserOnline();
                    //alert(IS_USER_ONLINE);

                    updateStatus('Y');
                    hideOverlay();
                });
                $("#stayOffline").click(function () {
                    updateStatus('N');
                    hideOverlay();
                });
                showNothing();
              });
        </script>

    </head>
    <body>
        <div id="selectAll"></div>
        <table width="100%" height="100%">
            <tr>
                <td colspan="3">
                    <h1>
                        RSS Reader Demo Using Google Gears [<span class="f8">Debug:</span> <span class="f8 cT" id="createTables">Create Tables</span> |
                        <span class="cT f8" id="deleteTables">Delete Tables</span> |
                        <span class="cT f8" id="removeStore">Remove Offline Pages</span> ]
                    </h1>
                </tr>
            </tr>
            <tr>
                <td colspan="2">
                    <div id="addSubscription" class="f10 addSub">
                        <span id="addSubLink" style="cursor:pointer"><img src="images/add.png"/>&nbsp; <u>Add Subscription</u></span>
                        <span id="delF" style="margin-left: 10px;font-size:11px;color:red;cursor:pointer">Delete Feeds</span>
                    </div>
                    <div id="addSubBox">
                        <form name="enterFeed" method="post">
                            <div style="padding: 5px;">
                                <div class="addSubX" id="addSubX">x</div>
                                <div>Please enter a feed url</div>
                                <div><input id="addSubTxt" type="text" size="32" /><input type="button" id="add" name="add" value="add" /></div>
                                <div>eg: http://feeds.feedburner.com/ajaxian</div>
                            </div>
                        </form>
                    </div>
                </td>
                <td align="right">
                    <span id="textOut" style="color:green;font-size:12px;font-weight:bold" >
                        <a href="javascript:createStore();">Make my Feeds Available Offline.</a>
                    </span>
                </td>
            </tr>
            <tr>
                <td height="100%" id="feedList" width="18%" valign="top">
                    <div id="feedListContainer"><!-- FEED LIST TO COME FROM DB --></div>
                </td>
                <td id="feedMenuSpacer" width="2%">&nbsp;</td>
                <td id="feedContent" valign="top" width="80%">
                </td>
            </tr>
        </table>

        <div id="offlinenotificationoverlay" class="modal-dialog" tabindex="0" role="wairole:dialog" labelledby=":8" style="left: 409px; top: 332px;display:none;">
            <div class="modal-dialog-title modal-dialog-title-draggable" id=":8">
                <span class="modal-dialog-title-text">Feed Reader is currently in offline mode.</span>
                <span class="modal-dialog-title-close"/>
            </div>
            <div class="modal-dialog-content">
                <div id="scour-disabled-element-error">
                    <p>The action you attempted can't be performed while <b>offline</b>.</p>
                </div>
            </div>
            <div class="modal-dialog-buttons">
                <button name="ok" id="goOnline">Go online</button>
                <button name="cancel" id="stayOffline">Stay in offline mode</button>
            </div>
        </div>
    </body>
</html>
